package com.person.webdemoproject2.controller;

import com.person.webdemoproject2.pojo.Collections;
import com.person.webdemoproject2.pojo.LikeResult;
import com.person.webdemoproject2.pojo.Post;
import com.person.webdemoproject2.pojo.Result;
import com.person.webdemoproject2.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/posts")
public class PostController {
    @Autowired
    private PostService postService;

    @PostMapping("/{postId}/like")
    public Result likePost(@PathVariable Integer postId,@RequestHeader String token) {
        log.info("Post like: " + postId);
        boolean b = postService.likePost(postId, token);
        int likeCount = postService.getLikeCount(postId);
        LikeResult likeResult = new LikeResult();
        if (b){

            likeResult.setLikeCount(likeCount);
            likeResult.setLiked(true);
            return Result.success(likeResult);
        }
        likeResult.setLikeCount(likeCount);
        likeResult.setLiked(false);
        return Result.success(likeResult);
    }
    @PostMapping("/collect")
    public Result collectPost(@RequestBody Collections collections, @RequestHeader String token) {
        log.info("用户收藏 {}" , collections.getPostid());

        if (postService.collectPost(collections,token)){
            return Result.success("收藏成功");
        }

        return Result.success("收藏失败,重复收藏");
    }
    @PostMapping("/{commentId}/likec")
    public Result likeComment(@PathVariable Integer commentId,@RequestHeader String token) {
        log.info("commentId: {} ", commentId);
        boolean b = postService.likeComment(commentId, token);
        int likeCount = postService.getLikecomment(commentId);
        LikeResult likeResult = new LikeResult();
        if (b) {
            likeResult.setLikeCount(likeCount);
            likeResult.setLiked(true);
            return Result.success(likeResult);
        }

        likeResult.setLikeCount(likeCount);
        likeResult.setLiked(false);
        return Result.success(likeResult);
    }
    @PutMapping("/update")
    public Result updatePost(@RequestBody Post post, @RequestHeader String token) {
        log.info("用户更改帖子内容");
        System.out.println(post.getTitle());
        System.out.println(post.getContent());
        if (postService.updatePost(post,token)) {
            return Result.success("更改成功");
        }

       return Result.error("更改失败");
    }
}
